package com.mychart.handler.ws;

import com.alibaba.fastjson2.JSON;
import com.mychart.data.LoginUserSussionRepository;
import com.mychart.entity.domain.WsReq;
import com.mychart.entity.domain.WsReq.WsReqType;
import com.mychart.entity.domain.WsRes;
import com.mychart.entity.mongo.ChartRecord;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import static com.mychart.constant.WsConstant.LOGIN_USER_NAME;
import static com.mychart.entity.domain.WsReq.WsReqType.*;
import static com.mychart.entity.domain.WsRes.WsResType.NEW_CHART_ADVICE;
import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;
import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_SINGLETON;


@Slf4j
public class UserWsHandler extends AbstractWebSocketHandler {

    LoginUserSussionRepository loginUserRepository;


    MongoTemplate mongoTemplate;

    public UserWsHandler(LoginUserSussionRepository loginUserRepository, MongoTemplate mongoTemplate) {
        this.loginUserRepository = loginUserRepository;
        this.mongoTemplate = mongoTemplate;
    }

    public String getUserName(WebSocketSession userSession) {
        Map<String, Object> attributes = userSession.getAttributes();
        return (String) attributes.get(LOGIN_USER_NAME);
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {

        String userName = getUserName(session);
        loginUserRepository.addLoginUser(userName,session);
        log.info(userName + " login!");
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        processMessage(message);
    }

    private void processMessage(WebSocketMessage<?> message) {
        String string = message.getPayload().toString();
        WsReq wsReq = JSON.parseObject(string, WsReq.class);
        switch (wsReq.getType()) {
            case CHART:processChart(wsReq.getContent());break;
            default:
                System.out.println("G");
        }
    }

    private void processChart(String content) {
        ChartRecord chartRecord = JSON.parseObject(content, ChartRecord.class);
        chartRecord.setDate(new Date());
        WebSocketSession webSocketSession = loginUserRepository.get(chartRecord.getTo());
        if (webSocketSession != null) {
            try {
                webSocketSession.sendMessage(
                        new TextMessage(
                                JSON.toJSONString(new WsRes(true,"new chart！",NEW_CHART_ADVICE,chartRecord))));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        mongoTemplate.insert(chartRecord);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        String userName = getUserName(session);
        loginUserRepository.userLogout(userName);
        log.info(userName + " logout!");
    }

//    @Override
//    public boolean supportsPartialMessages() {
//        return false;
//    }
}
